define(window.backboneCommon.getViewDefine("targetPack.index"), function ($,require,Collection,tpl) {
    var backboneView= Backbone.View.extend({
        events: {
            "click .global-listParam":"saveGlobalListParam",
            "click .delete-info": "deleteInfo"
        },
        initialize: function () {
            this.modelAttach={};
            this.modelAttach.customer=this.model.get("modelCustomer");
            this.listenTo(this.modelAttach.customer, 'bind:AllList', this.bindCustomer);
            this.listenTo(this.model, 'bind:PageList', this.bindList);
            this.listenTo(this.model, 'bind:StrategyList', this.bindHoverStrategy);
            this.listenTo(this.model, 'delete:Info', this.deleteInfoCallback);
            this.render();
        },
        render:function(){
            var templateHtml=_.template(tpl);
            this.$el.html(templateHtml());
            return this;
        },
        initMain:function(){
            this.elementModel={};
            this.extObject={};
            this.pageData={listParam:{},initExtObject:{}};
            this.elementModel.table=$("#tb_list");
            this._initPagePower();
        },
        _initPagePower:function(){
            var self=this;
            $.ExtAssist.rolePower.operatePage("list",["advertiserList"],function(json){
                self.pageData.powerInfo=json;
                self._initBodyMain();
                if(json["advertiserList"]){self.collection.getCustomer()}
            });
        },
        _initBodyMain:function(){
            this._initAssistCallback();
            this._getGlobalListParam();
            this._initInputSearch();
            this._initPageList();
        },
        _initAssistCallback:function(){
            var self=this;
            $.ExtAssist.winUnload.callback(function(){
                self._setGlobalListParam(null)
            });
        },
        _getGlobalListParam:function(){
            var data=$.ExtAssist.pageListParam.getData("targetPackList");
            if(data.search){$("#panel_inputSearch").data("initValue",data.search)}
            if(data.customer){$("#search_customer").data("initValue",data.customer)}
            this.pageData.listParam=data;
        },
        _setGlobalListParam:function(param){
            $.ExtAssist.pageListParam.setData("targetPackList",param);
        },
        saveGlobalListParam:function(){
            var param=$.ExtCommon.getJsonClone(this.pageData.listParam);
            param.offset=this.extObject.table.getCurrentOffset();
            this._setGlobalListParam(param);
        },
        _initInputSearch:function () {
            var self=this;
            self.extObject.inputSearch=$("#panel_inputSearch").ExtInputSearch({
                placeholder:"定向包ID,定向包名称",
                searchCallback:function () {
                    self.refreshList();
                }
            })
        },
        bindCustomer:function () {
            var self=this;
            var res=this.modelAttach.customer.get("dataAllList");
            var list=$.ExtCommon.convertListByPara(res.data,{name:"nameExt"});
            $("#search_customer").ExtSelect2({placeholder: "-广告主-",allowClear: true,minimumResultsForSearch: 1,infoExt:{data:list,
                initCallback:function(){self.pageData.initExtObject.customer=true},
                changeCallback:function(){self.refreshList()}
            }});
        },
        _getSearchParam:function(){
            var param={};
            var keyword = this.extObject.inputSearch.getValue();
            if (!$.ExtCommon.isCheckEmpty(keyword)) {param.search = keyword;}
            var customer="";
            if(this.pageData.initExtObject.customer){
                customer=$("#search_customer").val();
            }else{
                if(!$.ExtCommon.isCheckEmpty(this.pageData.listParam.customer)){customer=this.pageData.listParam.customer}
            }
            if (!$.ExtCommon.isCheckEmpty(customer)) {param.customer = customer;}
            return param;
        },
        _initPageList: function () {
            var self=this;
            var options={
                columns: [
                    {data: "id",class: "w-60"},
                    {data: "name",class: "w-min-100"},
                    {data: "customerName",class: "w-200"},
                    {data: null,class: "w-300"},
                    {data: "strategyCount", class: "w-100"},
                    {data: null, class: "w-100 text-center"}
                ],
                infoExt:{
                    ajaxDataPara:function(){
                        var param= {};
                        param= $.ExtCommon.initMergeJson(param,self._getSearchParam());
                        self.pageData.listParam = $.ExtCommon.getJsonClone(param);
                        return param;
                    },
                    ajaxWholeCallback:function(param){
                        self.collection.getPageList(param)
                    }
                },
                "createdRow": function (row, data) {
                    var elementTd=$('td', row);
                    var isPowerCustomer=self.pageData.powerInfo["advertiserList"];
                    var indexTarget=isPowerCustomer?3:2;
                    var indexStrategy=isPowerCustomer?4:3;
                    var indexOperate=isPowerCustomer?5:4;
                    elementTd.eq(indexTarget).html($.ExtCommon.getStringConnect('<div class="ellipsis-txt-title w-300" title="{0}">{0}</div>',[data.targetTag.join(",")]));
                    var countHtml=data.strategyCount===0
                        ?$.ExtCommon.getStringConnect('<span>{0}个策略</span>',[data.strategyCount])
                        :$.ExtCommon.getStringConnect('<span class="btn-operate longterm btn-not-link" id="hover_strategy_{0}" data-hover-type="">{1}个策略</span>',[data.id,data.strategyCount]);
                    elementTd.eq(indexStrategy).html(countHtml);
                    elementTd.eq(indexOperate).html('<a class="btn-operate longterm global-listParam" href="#tool/target/detail/'+data.id+'">编辑</a><a class="btn-operate longterm btn-operate-red delete-info" href="javascript:">删除</a>');
                },
                "drawCallback": function () {
                    self.elementModel.table.find('[data-hover-type]').each(function () {
                        var _this=$(this);
                        var tr = $(this).parents("tr:first");
                        var dataTr = self.extObject.table.getRowInfo(tr).data();
                        var id=dataTr.id;
                        _this.ExtPowerFloat({type:"table",
                            tableTitle:[
                                {key:"strategyName",title:"策略名称",class:"w-150",isEllipsis:true},
                                {key:"campaignName",title:"订单名称",class:"w-150",isEllipsis:true},
                                {key:"statusName",title:"状态",class:"w-60"}
                            ],
                            ajaxWholeCallback:function () {
                                var param= {};
                                param.id=id;
                                self.collection.getStrategyList(param)
                            }
                        });
                    });
                    $.ExtAssist.urlParam.setUrl();
                }
            };
            if(!$.ExtCommon.isCheckEmpty(self.pageData.listParam.offset)){options.displayStart=self.pageData.listParam.offset}
            options.columns[2]["visible"]=self.pageData.powerInfo["advertiserList"];
            self.extObject.table=self.elementModel.table.ExtDataTable(options);
        },
        bindList:function(){
            var data=this.model.get("dataPageList");
            this.extObject.table.ajaxWholeRefreshData(data);
        },
        refreshList: function () {
            this.closeHover();
            this.extObject.table.refresh()
        },
        closeHover:function() {
            if ($.powerFloat) $.powerFloat.hide();
        },
        bindHoverStrategy:function () {
            var result=this.model.get("dataStrategyList");
            $("#hover_strategy_"+result.req.id).ExtPowerFloat().ajaxWholeData(result.res.data);
        },
        deleteInfo:function (e) {
            var self = this;
            var tr = $(e.target).parents("tr:first");
            var rowData = this.extObject.table.getRowInfo(tr).data();
            $.ExtSweetAlert.confirmSimple("是否确定删除此定向？", "", function () {
                self.collection.deleteInfo(rowData.id);
            });
        },
        deleteInfoCallback: function () {
            var res=this.model.get("dataDeleteInfo");
            if (res.success) {
                this.refreshList();
                $.ExtNotify.success("删除成功!");
                $.ExtSweetAlert.checkClose(true);
            }else{
                $.ExtNotify.error(res.msg);
                $.ExtSweetAlert.checkClose(true);
            }
        }
    });
    var viewModel=function(){
        this.collection= new Collection();
        this.model=this.collection.model;
        this.view=new backboneView({ el: "#container_body",collection:this.collection,model:this.model});
    };
    viewModel.prototype={
        initView:function () {
            this.view.initMain();
        }
    };
    return viewModel;
});